<template>
  <el-dialog title="添加推荐" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">

    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="130px">
      <el-form-item label-width="0">
        <el-alert v-if="recommendList && recommendList.length > 0" type="info">
          您已将该内容推荐到 <el-tag v-for=" (item,index) in recommendList" :key="index" class="margin-r5">{{ item.display_name }}</el-tag><br>
          如果您继续选择了这些推荐位，将会同步更新为本次提交的内容。
        </el-alert>
      </el-form-item>
      <el-form-item label="推荐位" prop="recommendId">
        <recommend-selector v-model="model.recommend_keys" multiple></recommend-selector>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="model.title" placeholder="标题" />
      </el-form-item>
      <el-form-item label="标题图" prop="image">
        <el-input v-model="model.image_url" placeholder="标题图" />
        <image-single-selector v-model="image" class="single-img"></image-single-selector>
      </el-form-item>
      <el-form-item label="链接地址" prop="linkUrl">
        <el-input v-model="model.link_url" placeholder="链接地址" />
      </el-form-item>
      <el-form-item label="开始结束时间">
        <el-date-picker v-model="startEndTime" :picker-options="pickerOptions" :editable="false" unlink-panels type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="序号" prop="display_order">
        <el-input v-model="model.display_order" placeholder="序号" />
      </el-form-item>
      <el-form-item label="简介" prop="description">
        <el-input v-model="model.description" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" placeholder="简介" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { createRecommendItem, getRecommendsByItemId } from "@/api/business/recommend";
import RecommendSelector from "@/components/ApeSelectors/recommend-selector";
import ImageSingleSelector from "@/components/ApeSelectors/image-single-selector";
import { pickerOptions } from "@/utils/helpers/datetime-picker-helper";

export default {
  name: "ApeRecommendItemDialog",
  components: {
    ImageSingleSelector,
    RecommendSelector
  },
  data() {
    return {
      dialogVisible: false,
      isSubmitLoading: false,
      startEndTime: [],
      pickerOptions,
      image: undefined,
      recommendList: [],
      model: {
        item_type: "",
        item_id: "",
        recommend_keys: [],
        title: "",
        description: "",
        image_url: "",
        link_url: undefined,
        display_order: 0,
        start_time: undefined,
        end_time: undefined
      },
      modelRules: {
        recommend_keys: [{ required: true, trigger: "blur", message: "请选择推荐位" }],
        title: [{ required: true, trigger: "blur", message: "请输入标题" }]
      }
    };
  },
  watch: {
    // 如果 `image` 发生改变，这个函数就会运行
    image: function(newVal, oldVal) {
      this.model.image_url = newVal.url;
    }
  },
  methods: {
    show(itemType, itemId, title, description, imageUrl, linkUrl, display_order) {
      this.resetModal();
      this.model.item_type = itemType;
      this.model.item_id = itemId;
      this.model.title = title;
      this.model.description = description;
      this.model.image_url = imageUrl;
      this.model.link_url = linkUrl;
      this.model.display_order = display_order;

      if (itemType && itemId) {
        getRecommendsByItemId(itemType, itemId).then(result => {
          this.recommendList = result;

          this.dialogVisible = true;
          this.isSubmitLoading = false;
          this.$nextTick(() => {
            this.$refs["dataForm"].clearValidate();
          });
        });
      } else {
        this.dialogVisible = true;
        this.isSubmitLoading = false;
        this.$nextTick(() => {
          this.$refs["dataForm"].clearValidate();
        });
      }
    },
    resetModal() {
      this.model = {
        item_type: "",
        item_id: "",
        recommend_keys: [],
        title: "",
        description: "",
        image_url: "",
        link_url: undefined,
        display_order: 0,
        start_time: undefined,
        end_time: undefined
      };
      this.image = undefined;
    },
    save() {
      this.isSubmitLoading = true;
      this.$refs["dataForm"].validate(valid => {
        if (!valid) {
          this.isSubmitLoading = false;
          this.$message({ message: this.$t("formIsNotValidMessage"), type: "warning" });
          return;
        }

        const data = this.model;
        if (this.startEndTime && this.startEndTime.length > 0) {
          data.start_time = this.startEndTime[0];
          data.end_time = this.startEndTime[1];
        } else {
          data.start_time = undefined;
          data.end_time = undefined;
        }
        createRecommendItem(data).then(() => {
          this.$message({ message: "操作成功", type: "success" });
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.close();
          this.$emit("save");
        }).finally(() => {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
        });
      });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    }
  }
};
</script>
<style lang="scss">
.single-img {
  margin-top: 5px;
}
.margin-r5 {
  margin-right: 5px;
}
.el-select {
  display: block;
}
</style>
